<template>
  
  <div>
    <table>
      <tr>
        <th>书名</th>
        <th>作者</th>
        <th>借阅状态</th>
        <th>操作</th>
      </tr>
      <tr v-for="(book, index) in books" :key="index">
        <td>{{ book.title }}</td>
        <td>{{ book.author }}</td>
        <td>{{ book.status }}</td>
        <td>
          <button @click="editBook(index)">编辑</button>
          <button @click="deleteBook(index)">删除</button>
        </td>
      </tr>
    </table>

    <div>
      <h2>添加图书</h2>
      <form @submit.prevent="addBook">
        <input type="text" v-model="newBook.title" placeholder="书名" required>
        <input type="text" v-model="newBook.author" placeholder="作者" required>
        <input type="submit" value="添加图书">
      </form>
    </div>

    <div v-if="selectedBook !== null">
      <h2>编辑图书</h2>
      <form @submit.prevent="updateBook">
        <input type="text" v-model="selectedBook.title" placeholder="书名" required>
        <input type="text" v-model="selectedBook.author" placeholder="作者" required>
        <input type="submit" value="保存">
        <button @click="cancelEdit">取消</button>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      books: [
        { title: "Book 1", author: "Author 1", status: "在库" },
        { title: "Book 2", author: "Author 2", status: "已借出" },
        { title: "Book 3", author: "Author 3", status: "在库" },
      ],
      newBook: {
        title: "",
        author: "",
        status: "在库",
      },
      selectedBook: null,
    };
  },
  methods: {
    addBook() {
      this.books.push(this.newBook);
      this.newBook = {
        title: "",
        author: "",
        status: "在库",
      };
    },
    deleteBook(index) {
      this.books.splice(index, 1);
    },
    editBook(index) {
      this.selectedBook = { ...this.books[index] };
    },
    updateBook() {
      if (this.selectedBook !== null) {
        const index = this.books.findIndex(
          (book) => book.title === this.selectedBook.title && book.author === this.selectedBook.author
        );

        if (index !== -1) {
          this.books.splice(index, 1, this.selectedBook);
          this.selectedBook = null;
        }
      }
    },
    cancelEdit() {
      this.selectedBook = null;
    },
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  border: 1px solid black;
}

h2 {
  margin-top: 20px;
}

form {
  margin-bottom: 10px;
}
</style>
